<?php

namespace app\controller;

use Hashids\Hashids;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Request;
use app\traits\CommonTrait;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use app\traits\TemplateMsgTrait;

class Test
{
    use CommonTrait;
    use TemplateMsgTrait;

    //发送 统一服务消息
    public function sendTemplate()
    {
        $openId = 'oUjLs5fDwdeFJ7wGQrlWE9xhSYMA';
        $templateId = config('app.template.sample_notice');
        $pagePath = 'pakeageDaren/pages/accountList/index';
            $data = [
                "first" => [
                    "value" => "嗖嗖嗖，你申请的领样商品已经发货啦"
                ],
                "keyword1" => [
                    "value" => '福建宁德菌菇干货包45g包邮珍鲜汤包八珍汤'
                ],
                "keyword2" => [
                    "value" => '顺丰快递'
                ],
                "keyword3" => [
                    "value" => 'jw123456'
                ],
                "keyword4" => [
                    "value" => 'jw 18079160220 深圳'
                ],
                "remark" => [
                    "value" => "请您耐心等待"
                ],
            ];
            $result = $this->uniformMessageSend($openId, $templateId, $data,$pagePath);
        if ($result['code'] != 1) {
            return $this->apiJson($result['code'], $result['msg']);
        } else {
            return $this->apiJson(1, 'success', $result);
        }
    }

    public function sendMiniTemplate()
    {
        $accessToken = Cache::get('access_token');
        $client = new Client();
        if (!$accessToken) {
            $accessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . config('app.mp.appid') . '&secret=' . config('app.mp.secret');
            try {
                $response = $client->get($accessTokenUrl, ['timeout' => 5]);
            } catch (\Exception $e) {
                return $this->apiJson(-1, $e->getMessage());
            }
            $result = json_decode($response->getBody()->getContents(), true);
            if (isset($result['errcode'])) {
                return $this->apiJson(-1, $result['errmsg'], $result);
            }
            Cache::set('access_token', $result['access_token'], 7000);
            $accessToken = $result['access_token'];
        }
        $subscribeMsgUrl = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $accessToken;
        $payload = [
            'touser' => 'oUjLs5fDwdeFJ7wGQrlWE9xhSYMA',
            'template_id' => 'XfxLc4LIP-S9VLh7IAmzMeNdk0SWXSJr1FOHkM9MKFY',
            'data' => [
                "thing1" => [
                    "value" => "活动名称"
                ],
                "thing2" => [
                    "value" => "签退方式"
                ],
            ]
        ];
        try {
            $response = $client->post($subscribeMsgUrl, ['body' => json_encode($payload), 'debug' => true, 'headers' => ['Content-Type' => 'application/json'], 'timeout' => 5]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        return $this->apiJson(1, 'success', $result);
    }

    public function index()
    {
        $hashUid = 'nR';
        $hashIds = new Hashids();
        $userId = 154417;
        $hashUserId = $hashIds->encode($userId);
        $userIds = $hashIds->decode($hashUid);
        Log::info(1);
        Log::info($userIds);
        return $this->apiJson(1,'success',$hashUserId);
        $str = 'MS4wLjABAAAAvYFMjRhT_7pHVfgrEKSj4zAk6_UbPXdPjjJ51rlGQa7EklxqaZkMbUXxo3fApgDD';
        return $this->apiJson(1, '', md5($str));
        //e2cf820845f3345b9d0034929029b0c4
        $iv = substr(config('douyin.client_secret'), 0, 16);
        $encryptPhone = 'om10QfrJ7gGTo2t4CK1XEQ==';
        $phone = openssl_decrypt($encryptPhone, 'aes-256-cbc', config('douyin.client_secret'), 0, $iv);
        return $this->apiJson(1, 'success', $phone);
    }

    public function request()
    {
        $client = new Client();
        $url = "http://local.ddxia.com/api/test";

        $referUrl = "http://local.ddxia.com";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl,
            'Content-Type' => 'application/json,charset=utf-8'
        ];
        $payload = ['uid' => 1, 'name' => 'jw'];
        $cookies = config('app.buyin');
        $cookieJar = CookieJar::fromArray($cookies, 'buyin.jinritemai.com');
        try {
            // post form-data 请求
            $response = $client->post($url, ['body' => json_encode($payload), 'headers' => $headers, 'debug' => true, 'timeout' => 5, 'cookies' => $cookieJar]);
            //$response = $client->request('post', $url, ['form_params' => $payload,'headers'=>$headers,'debug'=>true,'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, 'fail', $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        return $this->apiJson(1, 'success', $result);
    }

    public function cookieToArray()
    {
        //$cookieStr = 'passport_csrf_token_default=2e1bfcdc65cb0c2614bd257b838de7fb; passport_csrf_token=2e1bfcdc65cb0c2614bd257b838de7fb; MONITOR_WEB_ID=1367cc38-d9c9-40b8-8754-fb4c9de0ab0d; ttcid=5910c4c5ec3c4558a9104c78e343e39423; csrf_session_id=923c504994af4d9c8ff76ffb2a96f034; csrf_token=uUIPewihPVSDuFtMdplMqbqDYISYzFNN; s_v_web_id=kp2p7euc_sxJAoFWA_hBQv_4jgq_BbVj_Hsi5QbqGTkOF; n_mh=q_Lw8p8dwgb91irwavm19tur3kRgafNXpsGC-eMrOnY; sso_uid_tt=a398f8215cb68d29330cf2e7cc91af05; sso_uid_tt_ss=a398f8215cb68d29330cf2e7cc91af05; toutiao_sso_user=4d672419c2b18f14f62edcbf4a82b270; toutiao_sso_user_ss=4d672419c2b18f14f62edcbf4a82b270; odin_tt=ff9d482fcf6ab56ab81afe031c02562f4b7bc9356dc0b5be40d4fd57002ec00575a4c3d6f40bdaceb73b57ce571c8f84; passport_auth_status_ss=391fb2b06eb03792a18dba90bbfda164%2C; sid_guard=d6132a6d9395d788a6829bc89df44482%7C1621866151%7C5184000%7CFri%2C+23-Jul-2021+14%3A22%3A31+GMT; uid_tt=8d40be7e728fdba2e6fe89478fabb661; uid_tt_ss=8d40be7e728fdba2e6fe89478fabb661; sid_tt=d6132a6d9395d788a6829bc89df44482; sessionid=d6132a6d9395d788a6829bc89df44482; sessionid_ss=d6132a6d9395d788a6829bc89df44482; passport_auth_status=391fb2b06eb03792a18dba90bbfda164%2C; oc_login_type=LOGIN_PERSON; ttwid=1%7CUFQJThWNEfu1-udHxpVabAaHCPl05Z3_BgY9i007bbQ%7C1621866170%7Cfe181cbf99baa9fd0345c0dd0197db3a03d68cb96a2a2e0dd36617c6f3b10e8c; tt_scid=Or07ZSxK2MqQvwnHKLFNEFa4FTz0HmmFA4fYAGQMqhVakeptL0BQ3Gv5pA7suiaE5ffc';
        $cookieStr = Request::post('cookie_str');
        $cookiePair = array_filter(explode('; ', $cookieStr));
        $cookie = [];
        if ($cookiePair) {
            foreach ($cookiePair as $v) {
                $perCookie = explode('=', $v);
                $cookie[$perCookie[0]] = $perCookie[1];
            }
        }
        Log::info($cookie);
        return $this->apiJson(1, '', $cookie);
    }
}
